﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using Microsoft.WindowsMobile.PocketOutlook;

namespace TestApplication3
{
    public partial class ctlMain : UserControl
    {
        private TestApplication3 owner;
        LocationData[] _locations;
        private bool SelectedChanged = false;
        LocationHandler mylocationhandler;
        Interfaces.ContextMatchesHandler del;
        
        public ctlMain(TestApplication3 _owner)

        {
            owner = _owner;
           
            InitializeComponent();
           // owner.
            mylocationhandler = new LocationHandler(_owner);
            RefreshTaskList();
            del = new Interfaces.ContextMatchesHandler(Contmatch);
            _locations = mylocationhandler.GetLocations();
        }

        //private void buttonSubscribe_Click(object sender, EventArgs e)
        //{
        //    Interfaces.PositionOriginator[] originators = { Interfaces.PositionOriginator.Cell, Interfaces.PositionOriginator.Wifi };
           // owner.Host.CreateEvent("test", 2, owner.ContextMatches, originators);
        //}
        void Contmatch(object obj, int i, short s)
        {

        }
        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControl1.SelectedIndex == 0)
            {
                RefreshTaskList();

            }
            if (tabControl1.SelectedIndex == 1)
            {
                RefreshLocationsListBox();
                RefreshAddLv2();
                
            }
            if (tabControl1.SelectedIndex == 2)
            {
                RefreshAddLv();
            }
        }

      

        private void RefreshLocationsListBox()
        {
            lbLocations.Items.Clear();
            _locations= mylocationhandler.GetLocations();
            if (_locations != null)
            {
                foreach (LocationData loc in _locations)
                {
                    lbLocations.Items.Add(loc.Name);

                }
            }
            lbLocations.Update();
            
        }

        private void RefreshTaskList()
    {
         OutlookSession AppSession = new OutlookSession();
                TaskCollection taskCol = AppSession.Tasks.Items;
                lBTasks.Items.Clear();
               // lBTasks.Items.Add("Add...");
                foreach (Task tasks in taskCol)
                {
                    lBTasks.Items.Add(tasks);
                }
                lBTasks.Update();
                AppSession.Dispose();
    }
        private void lBTasks_SelectedIndexChanged(object sender, EventArgs e)
        {

            if (lBTasks.SelectedIndex != -1)
            {
                bRemove.Enabled = true;
                SelectedChanged = true;
                Task temp = (Task)lBTasks.Items[lBTasks.SelectedIndex];
                tbSubject.Text = temp.Subject;
                tbBody.Text = temp.Body;
                dtPStartDate.Value = temp.StartDate;
                dtpDueDate.Value = temp.DueDate;
                cbLocReminder.Checked = false;
                cboxLoc.Items.Clear();
                bool IsContain = false;
                int selindex = 0;
                if (temp.Categories.Contains('#'))
                {

                    for (int i = 0; i < _locations.Length; i++)
                    {
                        cboxLoc.Items.Add(_locations[i].Name);

                        if (temp.Categories.Contains(_locations[i].Name))
                        {
                            IsContain = true;
                            selindex=i;
                        }
                    }
                    if(IsContain)
                    {
                        cbLocReminder.Checked = true;
                         cboxLoc.SelectedIndex=selindex;
                    }

                    //if (!cbLocReminder.Checked)
                    //{
                    //    string[] tempsplit = temp.Categories.Split(',');
                        
                    //    foreach (string str in temp)
                    //    {
                    //        if (!str.Contains('#'))
                    //        {
                    //            temp.Categories += str + ", ";
                    //        }

                    //    }

                    //}


                }
                
                  

                cbReminder.Checked = temp.ReminderSet;
                dtpReminderDate.Value = temp.ReminderTime.Date;
                //DateTime dt = new DateTime(
                //dt. .Hour = temp.ReminderTime.Hour;
                //dt.Second = temp.ReminderTime.Second;

                dtpReminderTime.Value = new DateTime(temp.ReminderTime.Ticks);
                SelectedChanged = false;
                bSave.Enabled = false;
            }
            else
                bRemove.Enabled = false;

            UpdateDateTPState();
        }

        private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
        {
            if(!SelectedChanged)
            EnableSaveButton();
        }

        private void tbSubject_TextChanged(object sender, EventArgs e)
        {
            if (!SelectedChanged)
            EnableSaveButton();
        }

        private void dtpDueDate_ValueChanged(object sender, EventArgs e)
        {
            if (!SelectedChanged)
            EnableSaveButton();
        }

        private void dtpReminderDate_ValueChanged(object sender, EventArgs e)
        {

            if (!SelectedChanged)
            EnableSaveButton();
        }

        private void dtpReminderTime_ValueChanged(object sender, EventArgs e)
        {
            if (!SelectedChanged)
            EnableSaveButton();
        }

       
        private void cbReminder_CheckStateChanged(object sender, EventArgs e)
        {
            if (!SelectedChanged)
                EnableSaveButton();
            UpdateDateTPState();
        }

        private void UpdateDateTPState()
        {
            if (cbReminder.Checked)
            {
                dtpReminderDate.Enabled = true;
                dtpReminderTime.Enabled = true;
            }
            else
            {
                dtpReminderDate.Enabled = false;
                dtpReminderTime.Enabled = false;
            }
            if (cbLocReminder.Checked)
            {
                cboxLoc.Enabled = true;
            }
            else
            {
                cboxLoc.Enabled = false;
            }
        }
        private void cbLocReminder_CheckStateChanged(object sender, EventArgs e)
        {
            if (!SelectedChanged)
            EnableSaveButton();
            UpdateDateTPState();
            if (cbLocReminder.Checked)
            {
                cboxLoc.Items.Clear();
                for (int i = 0; i < _locations.Length; i++)
                {
                    cboxLoc.Items.Add(_locations[i].Name);
                }
            }
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!SelectedChanged)
            EnableSaveButton();
        }

        private void tbBody_TextChanged(object sender, EventArgs e)
        {
            if (!SelectedChanged)
            EnableSaveButton();
        }

        private void EnableSaveButton()
        {
            bSave.Enabled = true;
        }

        private void bAdd_Click(object sender, EventArgs e)
        {
           
          
            lBTasks.SelectedIndex = -1;
            ClearInputFields();
        }

        private void bRemove_Click(object sender, EventArgs e)
        {
            OutlookSession AppSession = new OutlookSession();
            AppSession.Tasks.Items.Remove((Task)lBTasks.SelectedItem);
            AppSession.Dispose();
            lBTasks.Items.Remove(lBTasks.SelectedItem);
            ClearInputFields();
            
        }

        private void ClearInputFields()
        {
            tbBody.Text = "";
            tbSubject.Text = "";
            cbLocReminder.Checked = false;
            cbReminder.Checked = false;
            dtpDueDate.Value = DateTime.Now;
            dtpReminderTime.Value = DateTime.Now;
            dtPStartDate.Value = DateTime.Now;
        }
        private void bSave_Click(object sender, EventArgs e)
        {
            bSave.Enabled = false;
            OutlookSession AppSession = new OutlookSession();
            Task newtask=new Task();
          //  Task temp = (Task)lBTasks.Items[lBTasks.SelectedIndex];
            if (lBTasks.SelectedIndex != -1)
            {
                // newtask = ((Task)lBTasks.SelectedItem).Copy();
                
                newtask = ((Task)lBTasks.SelectedItem).Copy();

               // newtask = new Task(((Task)lBTasks.SelectedItem).ItemId);
                    AppSession.Tasks.Items.Remove((Task)lBTasks.SelectedItem);
            }
           
            newtask.Subject= tbSubject.Text;
            newtask.StartDate=dtPStartDate.Value;
            newtask.DueDate=dtpDueDate.Value;
            newtask.ReminderSet=cbReminder.Checked;
            newtask.ReminderTime= dtpReminderDate.Value;
            newtask.ReminderTime = newtask.ReminderTime.AddHours((double)dtpReminderTime.Value.Hour);
            newtask.ReminderTime = newtask.ReminderTime.AddMinutes((double)dtpReminderTime.Value.Minute);
            newtask.Body=tbBody.Text;
            
                if (newtask.Categories.Contains('#'))
                {
                    string[] temp = newtask.Categories.Split(',');
                    newtask.Categories = "";
                    foreach (string str in temp)
                    {
                        if (!str.Contains('#'))
                        {
                            newtask.Categories += str + ", ";
                        }

                    }

                    //newtask.Categories.IndexOf('#');
                }
                
                if (cbLocReminder.Checked)
                {
                    if (newtask.Categories != "")
                        newtask.Categories += ", ";
                    newtask.Categories += '#' + cboxLoc.SelectedItem.ToString() + '#';

                }
           
           
            
            if(lBTasks.SelectedIndex==-1)
            AppSession.Tasks.Items.Add(newtask);
            else
            newtask.Update();
            //feliratkozni értesítésre
            if(cbLocReminder.Checked)
            mylocationhandler.AddLocationEvent(newtask.ItemId.ToString(), _locations[cboxLoc.SelectedIndex]);

            AppSession.Dispose();
            RefreshTaskList();
        }

        private void bSavenewLoc_Click(object sender, EventArgs e)
        {
            if (tbNewLocName.Text != "" && lvActualPositions.Items.Count>0)
            {
                LocationData newloc = new LocationData();
                newloc.Name = tbNewLocName.Text;
                List<string> postemp = new List<string>();
                
                for (int i = 0; i < lvActualPositions.Items.Count; i++)
                {
                    if(lvActualPositions.Items[i].Checked)
                        postemp.Add(lvActualPositions.Items[i].Text);

                }
                if (postemp != null)
                    newloc.PositonsHashes = postemp.ToArray();
                mylocationhandler.SaveNewLocation(newloc);
               
            }
         
        }

        private void brefresh_Click(object sender, EventArgs e)
        {
            RefreshAddLv2();
            RefreshAddLv();
        }

        private void RefreshAddLv()
        {
            Interfaces.PositionOriginator[] originators = { Interfaces.PositionOriginator.Cell, Interfaces.PositionOriginator.Wifi };
            string[] pos = owner.Host.GetCurrentContext(originators);
            lvActualPositions.Items.Clear();
           
            foreach (string acthash in pos)
            {
                ListViewItem listv = new ListViewItem();

                listv.Text = acthash;
                if(acthash.Length<13)
                    listv.SubItems.Add("Cell");
                else
                    listv.SubItems.Add("Wifi");
                lvActualPositions.Items.Add(listv);
                

            }
           lvActualPositions.Update();
            
        }
        private void RefreshAddLv2()
        {
            Interfaces.PositionOriginator[] originators = { Interfaces.PositionOriginator.Cell, Interfaces.PositionOriginator.Wifi };
            string[] pos = owner.Host.GetCurrentContext(originators);
           
            lvActualLoc.Items.Clear();
            foreach (string acthash in pos)
            {
                ListViewItem listv = new ListViewItem();

                listv.Text = acthash;
                if (acthash.Length < 13)
                    listv.SubItems.Add("Cell");
                else
                    listv.SubItems.Add("Wifi");
                
                lvActualLoc.Items.Add(listv);

            }
           
            lvActualLoc.Update();
        }

        private void lbLocations_SelectedIndexChanged(object sender, EventArgs e)
        {
            lvLocationsItem.Items.Clear();
           

                string[] temp = _locations[lbLocations.SelectedIndex].PositonsHashes;
                foreach (string pos in temp)
                {
                    ListViewItem listv = new ListViewItem();

                    listv.Text = pos;
                    if (pos.Length < 13)
                        listv.SubItems.Add("Cell");
                    else
                        listv.SubItems.Add("Wifi");
                    lvLocationsItem.Items.Add(listv);
                }
                lvLocationsItem.Update();
            
        }

        private void bRemoveLoc_Click(object sender, EventArgs e)
        {
            mylocationhandler.RemoveLocation(_locations[lbLocations.SelectedIndex]);
            RefreshLocationsListBox();
            lvLocationsItem.Items.Clear();
        }

        private void bAddPositon_Click(object sender, EventArgs e)
        {
            List<string> tempstrings =new List<string>();
            foreach (string temp in _locations[lbLocations.SelectedIndex].PositonsHashes)
            {
                tempstrings.Add(temp);
            }
           
            
            
            for (int i = 0; i < lvActualLoc.Items.Count; i++)
			{
			 if(lvActualLoc.Items[i].Checked)
             {
                 tempstrings.Add(lvActualLoc.Items[i].Text);
             }
			}


            
            mylocationhandler.ChangeLocationItems(_locations[lbLocations.SelectedIndex],tempstrings.ToArray());
            _locations = mylocationhandler.GetLocations();
            RefreshLocationsListBox();
            lvLocationsItem.Items.Clear();
            RefreshAddLv2();
        }

        private void bRemovePositions_Click(object sender, EventArgs e)
        {
            List<string> tempstrings =new List<string>();
           for (int i = 0; i < lvLocationsItem.Items.Count; i++)
			{
               if(!lvLocationsItem.Items[i].Checked)
               {
                   tempstrings.Add(lvLocationsItem.Items[i].Text);
               }
           }
               mylocationhandler.ChangeLocationItems(_locations[lbLocations.SelectedIndex], tempstrings.ToArray());
               _locations = mylocationhandler.GetLocations();
               RefreshLocationsListBox();
               lvLocationsItem.Items.Clear();
               RefreshAddLv2();
			 
			
            
        }
       
    }
}
